package com.example.spring_trans.controller;

import com.example.spring_trans.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.sql.DataSourceDefinition;

/**
 * ClassName: UserController
 * Package: IntelliJ IDEA
 * Description:
 *
 * @Author 谷京京
 * @Create 2024/3/19 22:25
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @RequestMapping("/registry")
    public String registry(String userName, String password) {
        //开启事务
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        Integer result = userService.insertUser(userName, password);
        log.info("用户插入成功, result:"+result);
//        //回滚事务
//        dataSourceTransactionManager.rollback(transactionStatus);
        //提交事务
        dataSourceTransactionManager.commit(transactionStatus);
        return "注册成功";
    }
}
